package com.itheima.project.handler.alipay.config;

import com.alipay.easysdk.kernel.Config;
import com.itheima.project.constant.trade.TradingConstant;
import com.itheima.project.core.enums.trade.TradingEnum;
import com.itheima.project.exception.ProjectException;
import com.itheima.project.face.PayChannelFace;
import com.itheima.project.utils.EmptyUtil;
import com.itheima.project.vo.trade.PayChannelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Async;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collectors;

/**
 * @ClassName AlipayConfig.java
 * @Description 支付宝配置类
 */
@Slf4j
@Configuration
public class AlipayConfig {

    @Autowired
    PayChannelFace payChannelFace;

    @Async
    @PostConstruct
    public void initConfig(){
        Timer timer = new Timer();
        timer.schedule(new InitTask(timer),10*1000);
    }

    class InitTask extends TimerTask {

        private Timer timer;

        private InitTask(Timer timer) {
            this.timer= timer;
        }

        @Override
        public void run() {
            //初始化阿里云SMS的配置信息
            payChannelFace.findPayChannelList(TradingConstant.TRADING_CHANNEL_ALI_PAY);
        }
    }

    /***
     * @description 获得配置
     * @return
     */
    public Config queryConfig(Long enterpriseId ){
        //1、缓存配置
        List<PayChannelVo> payChannelVos = payChannelFace.findPayChannelList(TradingConstant.TRADING_CHANNEL_ALI_PAY);
        if (EmptyUtil.isNullOrEmpty(payChannelVos)){
            throw  new ProjectException(TradingEnum.CONFIG_EMPT);
        }
        List<PayChannelVo> payChannelVoRestult = payChannelVos.stream()
                .filter(n -> n.getEnterpriseId().longValue() == enterpriseId.longValue())
                .collect(Collectors.toList());
        //2、配置信息校验
        if (EmptyUtil.isNullOrEmpty(payChannelVoRestult)&&payChannelVoRestult.size()>1){
            throw  new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        PayChannelVo payChannelVo = payChannelVoRestult.get(0);
        //2、创建配置
        Config config = new Config();
        config.protocol = "https";
        config.gatewayHost =payChannelVo.getDomain();
        config.signType = "RSA2";
        config.appId = payChannelVo.getAppId();
        //2.1、配置应用私钥
        config.merchantPrivateKey = payChannelVo.getMerchantPrivateKey();
        //2.2、配置支付宝公钥
        config.alipayPublicKey = payChannelVo.getPublicKey();
        //2.3、可设置异步通知接收服务地址（可选）
        config.notifyUrl = payChannelVo.getNotifyUrl();
        //2.4、设置AES密钥，调用AES加解密相关接口时需要（可选）
        config.encryptKey = payChannelVo.getEncryptKey();
        //2.5、配置信息放入configHashMap中
        return config;
    }

}
